"""
日志配置模块
"""
import logging
import logging.handlers
import os
from pathlib import Path

def setup_logging(name='celery', level=None):
    """
    设置日志配置
    
    Args:
        name: 日志名称
        level: 日志级别
    
    Returns:
        Logger实例
    """
    # 创建日志目录
    log_dir = Path('/var/log/celery')
    log_dir.mkdir(parents=True, exist_ok=True)
    
    # 获取日志级别
    if level is None:
        level = os.getenv('LOG_LEVEL', 'INFO')
    
    # 创建logger
    logger = logging.getLogger(name)
    logger.setLevel(getattr(logging, level.upper()))
    
    # 清除现有处理器
    logger.handlers.clear()
    
    # 控制台处理器
    console_handler = logging.StreamHandler()
    console_handler.setLevel(logging.DEBUG)
    
    # 文件处理器（按天轮转）
    file_handler = logging.handlers.TimedRotatingFileHandler(
        filename=log_dir / f'{name}.log',
        when='midnight',
        interval=1,
        backupCount=30,
        encoding='utf-8'
    )
    file_handler.setLevel(logging.INFO)
    
    # 错误文件处理器
    error_handler = logging.handlers.RotatingFileHandler(
        filename=log_dir / f'{name}_error.log',
        maxBytes=10 * 1024 * 1024,  # 10MB
        backupCount=5,
        encoding='utf-8'
    )
    error_handler.setLevel(logging.ERROR)
    
    # 设置格式
    formatter = logging.Formatter(
        '[%(asctime)s] [%(name)s] [%(levelname)s] [%(process)d] [%(task_id)s] %(message)s',
        datefmt='%Y-%m-%d %H:%M:%S'
    )
    
    console_handler.setFormatter(formatter)
    file_handler.setFormatter(formatter)
    error_handler.setFormatter(formatter)
    
    # 添加处理器
    logger.addHandler(console_handler)
    logger.addHandler(file_handler)
    logger.addHandler(error_handler)
    
    return logger

class TaskLoggerAdapter(logging.LoggerAdapter):
    """任务日志适配器，添加任务ID"""
    
    def process(self, msg, kwargs):
        """处理日志消息"""
        task_id = self.extra.get('task_id', 'N/A')
        return msg, {'extra': {'task_id': task_id}}